package docker

import (
	"context"
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/client"
	. "go_learn/constant"
	"log"
)

func RemoveContainerList(url string, nsList []string) error {
	for _, sn := range nsList {
		if err := RemoveContainer(url, sn); err != nil {
			return err
		}
	}
	return nil
}

func RemoveContainer(url string, name string) error {
	cli, err := client.NewClient(url, "1.27", nil, nil)
	if err != nil {
		return err
	}

	args := filters.NewArgs()
	args.Add("name", name)
	listOptions := types.ContainerListOptions{
		All:     true,
		Filters: args,
	}
	containerList, err := cli.ContainerList(context.Background(), listOptions)
	if err != nil {
		return err
	}
	var containerID string
	if len(containerList) > 0 {
		for _, container := range containerList {
			fmt.Println(container.Names)
			if container.Names[0] == name {
				containerID = container.ID
				log.Printf("container name: %s, container id: %s", name, container.ID)
			}
		}
	} else {
		log.Printf("not found kubelet or kube-proxy container")
		return nil
	}

	// ? 等于true会kill失败
	removeOptions := types.ContainerRemoveOptions{
		RemoveVolumes: false,
		RemoveLinks:   false,
		Force:         true,
	}

	if err := cli.ContainerRemove(context.Background(), containerID, removeOptions); err != nil {
		return err
	}
	return nil
}

func GetDockerApiUrl(host string) string {
	return "http://" + host + DOCKER_API_PORT
}

func main() {
	hosts := []string{"20.26.38.125"}
	url := GetDockerApiUrl(hosts[0])
	name := "/kubelet"
	if err := RemoveContainer(url, name); err != nil {
		fmt.Println(err)
	}
}
